package com.lele.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lele.mapper.MenuMapper;
import com.lele.pojo.Admin;
import com.lele.pojo.Menu;
import com.lele.pojo.Role;
import com.lele.service.IAdminService;
import com.lele.service.IMenuService;
import kotlin.jvm.internal.Lambda;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.security.Principal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lele
 * @since 2022-11-26
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {
    @Resource
    private MenuMapper menuMapper;




    @Override
    //可以指定多个缓存名称，只要有一个命中就直接返回
    @Cacheable(value = {"menus"})
    public List<Menu> getMenuById() {
        //获取到princlpal，里面有对应的name
        //TODO为什么principal可以直接转为Admin
        Admin admin = (Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<Menu> menuList=menuMapper.getAdminInfoByPrincipal(admin.getId());
        return menuList;
    }

    @Override
    public List<Menu> getMenuWithRole() {
        List<Menu> menuList=this.baseMapper.getMenuWithRole();
        return menuList;
    }

    @Override
    public List<Menu> getAllMenu() {
        List<Menu> menus = menuMapper.selectList(null);
        //首先遍历出根节点，然后获得孩子节点
        List<Menu> collect = menus.stream().filter(item -> {
            return item.getParentId() == 0;
        }).map(item -> {
            item.setChildren(getMenuChild(item, menus));
            return item;
        }).collect(Collectors.toList());
        return collect;
    }

    private List<Menu> getMenuChild(Menu root, List<Menu> menus) {
        List<Menu> collect = menus.stream().filter(item -> {
            //TODO equals后面的值可以为null，将不确定的值放在后面
            return root.getId().equals(item.getParentId());
        }).map(item -> {
            item.setChildren(getMenuChild(item, menus));
            return item;
        }).collect(Collectors.toList());
        return collect;
    }

}
